package demo1;

public class HashBucket {
    private static class Node {
        private int key;
        private int value;
        Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public int put(int key, int value) {
        // write code here
        int index = key % array.length;
        Node cur = array[index];

        while(cur != null) {
            if(cur.key == key) {
                cur.value = value;
                return 0;
            }
            cur = cur.next;
        }

        Node node = new Node(key, value);
        cur = array[index];
        if(cur == null) cur = node;
        else {
            while(cur.next != null) cur = cur.next;
            cur.next = node;
        }
        size++;

        if(loadFactor() >= LOAD_FACTOR) resize();

        return 0;
    }


    private void resize() {
        // write code here
        Node[] newArray = new Node[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            Node tmp = cur.next;
            while(cur != null) {
                int newIndex = cur.key % newArray.length;
                Node node = newArray[newIndex];
                if(node != null) {
                    while(node.next != null) node = node.next;
                    node.next = cur;
                }else newArray[newIndex] = cur;
                cur.next = null;
                cur = tmp.next;
            }
        }
    }

    private double loadFactor() {
        return size * 1.0 / array.length;
    }


    public HashBucket() {
        // write code here
    }

    public int get(int key) {
        // write code here
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) return cur.value;
            cur = cur.next;
        }
        return -1;
    }
}
